package cn.kailangtu.dataspot.services;

import android.os.SystemClock;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import cn.kailangtu.commontools.CommonUtils;
import cn.kailangtu.modbus.ModbusSlave;

public class SocketContext {
    private byte[] bufArray;
    private boolean run = true;
    private Socket socket;
    InputStream ins;
    OutputStream ons;
    public void build(Socket socket)
    {
        startReader(socket);
    }

    /**
     * 从参数的Socket里获取消息
     */
    private void startReader(Socket mSocket) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ins = mSocket.getInputStream();
                    ons = mSocket.getOutputStream();

                    while(run) {
                        byte[] buf = new byte[1024];
                        int readCount = ins.read(buf);
                        if (readCount > 0) {
                            received(buf,readCount);

                        }
                        SystemClock.sleep(10);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    public void sendData(byte[] data){
        try {
            ons.write(data);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private  void received(byte[] array,
                                 int size) {
        bufArray = CommonUtils.ArrayAppend(
                bufArray, array, size);
        if(bufArray != null) {
            Log.d("SOCKETSOCKET_SERVER_RECEIVE", CommonUtils.ByteArrayToHexString(bufArray));
            //Com5.getInstance().sendData(bufArray);
            if (bufArray.length >= 12) {
                byte[] receive = ModbusSlave.executeTcp(bufArray);
                if (receive != null) {
                    Log.d("SOCKETSOCKET_SERVER_SEND", CommonUtils.ByteArrayToHexString(receive));
                    sendData(receive);
                }
                bufArray = null;
            }
        }
    }

    public void close()
    {
        run = false;
        // 取消定时器
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            socket = null;
        }

    }
}
